//
//  REClassifyLocalFileViewController.m
//  录音
//
//  Created by ywy on 2016/12/28.
//  Copyright © 2016年 Wely. All rights reserved.
//

#import "REClassifyLocalFileViewController.h"
#import "RESelectAlbumViewController.h"
#import "RETabBarViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "RECheckLogin.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "RESingleton.h" // 数据库



@interface REClassifyLocalFileViewController ()<UITextFieldDelegate,AVAudioPlayerDelegate>


@property (nonatomic, strong) AVPlayer   *selfPlayer;
@property(nonatomic,assign) BOOL ispaly;

// 一级分类的id
@property(nonatomic,copy)  NSString * firstStr;
// 二级分类的id
@property(nonatomic,copy)  NSString * secondStr;
//三级分类的id
@property(nonatomic,copy)  NSString * thirdStr;

// 一级分类的数组
@property(nonatomic,strong) NSMutableArray * firstArr;
// 二级分类的数组
@property(nonatomic,strong) NSMutableArray * secondArr;
// 三级分类的数组
@property(nonatomic,strong) NSMutableArray * thirdArr;
@end

@implementation REClassifyLocalFileViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    RETabBarViewController * tabBar = (RETabBarViewController *)self.tabBarController;
    //自定义隐藏Tabbar
    [tabBar HideTabarView:YES];
    UIImageView * firstImageView  =[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"归类本地文件"]];
    firstImageView.frame = CGRectMake(0, 0, 37, 17);
    self.navigationItem.titleView=firstImageView;
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(backPop)];
    self.navigationItem.leftBarButtonItem = rightItem;
}

-(void)backPop
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.ispaly = YES;
    self.firstArr = [NSMutableArray new];
    self.secondArr = [NSMutableArray new];
    self.thirdArr = [NSMutableArray new];
    self.nameTextField.layer.borderColor = RERGBColor(234, 234, 234).CGColor;
    self.albumNameTextField.layer.borderColor = RERGBColor(234, 234, 234).CGColor;
    
    self.nameTextField.delegate = self;
    self.albumNameTextField.delegate = self;
    UIView *blankViewFirst = [[UIView alloc] initWithFrame:CGRectMake(self.albumNameTextField.frame.origin.x,self.albumNameTextField.frame.origin.y,5.0, self.albumNameTextField.frame.size.height)];
    self.albumNameTextField.leftView = blankViewFirst;
    self.albumNameTextField.leftViewMode =UITextFieldViewModeAlways;
    
    UIView *blankView = [[UIView alloc] initWithFrame:CGRectMake(self.nameTextField.frame.origin.x,self.nameTextField.frame.origin.y,5.0, self.nameTextField.frame.size.height)];
    self.nameTextField.leftView = blankView;
    self.nameTextField.leftViewMode =UITextFieldViewModeAlways;
    [self.albumNameTextField setEnabled:NO];
    
   [self.progressView setTrackTintColor:RERGBColor(249, 182, 70)];
    self.progressView.layer.masksToBounds = YES;
    self.progressView.layer.cornerRadius = 5;
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
    [self.bottomView addGestureRecognizer:tap];
    [self setDataUp];
    // Do any additional setup after loading the view from its nib.
}
-(void)setDataUp
{
    self.totalTime.text = [NSString stringWithFormat:@"/ %@",self.baseModel.currentTime];
    self.proserLabel.text   =  @"00:00";
    if ([self.baseModel.titleStr isEqualToString:@"RE"]) {
        self.titleLabel.text = @"未命名";
    }else
    {
        self.titleLabel.text = self.baseModel.titleStr;
        self.nameTextField.text =self.baseModel.titleStr;
        self.firstStr = self.baseModel.firstStr;
        self.secondStr = self.baseModel.secondStr;
        self.thirdStr = self.baseModel.thirdStr;
        self.albumNameTextField.text  =  self.baseModel.albumName;
        // self.baseModel.albumName
    }
}

-(void)tapClick{
    __weak typeof(self) weakSelf = self;
    RESelectAlbumViewController * selectVC = [[RESelectAlbumViewController alloc] init];
    selectVC.albumBlock = ^(REThirdClassification *model,NSString * firstStr,NSString * secondStr,NSString * thirdStr)
    {
        weakSelf.albumNameTextField.text = [NSString stringWithFormat:@"%@",model.thirdTypeName];
        weakSelf.firstStr = firstStr;
        weakSelf.secondStr = secondStr;
        weakSelf.thirdStr = thirdStr;
    };
    [self.navigationController pushViewController:selectVC animated:YES];
}

- (IBAction)playClick:(UIButton *)sender {
    sender.selected = ! sender.selected;
    if (sender.selected == YES) {
        if (self.ispaly) {
            [self.selfPlayer.currentItem removeObserver:self  forKeyPath:@"status"];
            [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
          
            AVAudioSession *session = [AVAudioSession sharedInstance];
            [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
//            [session setCategory:AVAudioSessionCategoryPlayback error:nil];
            [session setActive:YES error:nil];
            
            NSURL *localURL = [NSURL fileURLWithPath:[RECheckLogin getlocalPath:@"/" allStr:self.baseModel.baseUrl]];
            AVURLAsset *localAssert = [[AVURLAsset alloc]initWithURL:localURL options:nil];
            //AVPlayerItem 他是对assert对应资源的一种整体描述，包括能够播放，以及影片长度等内容
            AVPlayerItem *item = [[AVPlayerItem alloc]initWithAsset:localAssert];
            //使用item生成player，这里会对影片进行预加载分析，然后更新item的状态
            self.selfPlayer = [AVPlayer playerWithPlayerItem:item];
            self.selfPlayer.volume = 1;            
            //监听AVPlayerItem的status状态，当status状态为readyToPlayer时，我们认为影片时可以播放的
            [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.selfPlayer.currentItem];
        }else
        {
            [self.selfPlayer play];
        }
    }else
    {
        // stop
        [self.selfPlayer pause];
        self.ispaly = NO;
    }
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    __weak typeof(self) weakSelf = self;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItem *item = (AVPlayerItem*)object;
        if (item.status == AVPlayerItemStatusReadyToPlay) {
            //这里影片可以播放
            [self.selfPlayer play];
            [self.selfPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
                //time是指当前影片播放的时间
                //得到影片的总时间
                CMTime totalTime = weakSelf.selfPlayer.currentItem.duration;
                //CMTimeGetSeconds 把CMTime转换为秒数
                CGFloat currentTimeSeconds = CMTimeGetSeconds(time);
                CGFloat totalSeconds = CMTimeGetSeconds(totalTime);
                int  minnute = currentTimeSeconds/60;
                int second = currentTimeSeconds-minnute*60;
                weakSelf.proserLabel.text = [NSString stringWithFormat:@"%02d:%02d",minnute,second];
                //更新进度
                [weakSelf.progressView setProgress:currentTimeSeconds*1.0/totalSeconds animated:YES];
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:@"录音文件暂时无法播放"];
        }
    }
    
}

- (void)playbackFinished:(NSNotification *)notifi {
    self.progressView.progress = 0.0;
    [self.palyButton setSelected:NO];
    self.ispaly = YES;
}

// 这是一个推荐的 按钮
- (IBAction)recommendClick:(UIButton *)sender {
     __weak typeof(self) weakSelf = self;
    RESelectAlbumViewController * selectVC = [[RESelectAlbumViewController alloc] init];
    selectVC.albumBlock = ^(REThirdClassification *model,NSString * firstStr,NSString * secondStr,NSString * thirdStr)
    {
        weakSelf.albumNameTextField.text = model.thirdTypeName;
        weakSelf.firstStr = firstStr;
        weakSelf.secondStr = secondStr;
        weakSelf.thirdStr = thirdStr;
    };
    [self.navigationController pushViewController:selectVC animated:YES];
}




-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [textField resignFirstResponder];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    if (range.location>=14)
    {
        [SVProgressHUD showErrorWithStatus:@"文字个数0-14"];
        return  NO;
    }
    else
    {
        return YES;
    }
    
    
    
    return YES;

}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (!textField.text || textField.text == nil || [textField.text  isEqualToString:@" "] || textField.text.length == 0) {
            self.titleLabel.text = @"[未命名]";
    }else
    {
            self.titleLabel.text = textField.text;
    }
}

// 保存    更新数据库的 信息
- (IBAction)saveClick:(UIButton *)sender {
    // 追加字符串的 数据到  沙盒的路径下面
    if (self.albumNameTextField.text.length == 0 || self.albumNameTextField.text == nil) {
        [SVProgressHUD showErrorWithStatus:@"请选择专辑名称"];
        return;
    }
    [self creatFile];
    
    
    
    if ([self.noclassStr isEqualToString:@"noClass"] ) {
        // 更新所有的id  一级二级 三级  曲目名字 专辑名字
        BOOL isSuccess = [[RESingleton defaultCent] ModifyTheDateWithBaseUrl:self.baseModel.baseUrl
                                                                    firstStr:self.firstStr
                                                                   secondStr:self.secondStr
                                                                    thirdStr:self.thirdStr
                                                                   albumName:self.albumNameTextField.text
                                                                    titleStr:self.titleLabel.text];
        if (isSuccess == YES) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateTheDatabase" object:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }else
        {
            [SVProgressHUD showErrorWithStatus:@"更新数据库失败!!!!!"];
        }

    }else
    {
        
        if ([self.baseModel.idStr isEqualToString:@"00000"]) {
            // 更新所有的id  一级二级 三级  曲目名字 专辑名字
            BOOL isSuccess = [[RESingleton defaultCent] ModifyTheDateWithBaseUrl:self.baseModel.baseUrl
                                                                        firstStr:self.firstStr
                                                                       secondStr:self.secondStr
                                                                        thirdStr:self.thirdStr
                                                                       albumName:self.albumNameTextField.text
                                                                        titleStr:self.titleLabel.text];
            if (isSuccess == YES) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"updateTheDatabase" object:nil];
                [self.navigationController popViewControllerAnimated:YES];
            }else
            {
                [SVProgressHUD showErrorWithStatus:@"更新数据库失败!!!!!"];
            }

        }else
        {
            
            NSMutableDictionary * dict = [NSMutableDictionary new];
            dict[@"cmd"] = @"updateType";
            dict[@"uid"] = [UserDefaults objectForKey:@"userid"];
            dict[@"albumid"] =  self.baseModel.idStr;
            dict[@"firstTypeId"] = self.firstStr;
            dict[@"secondTypeId"] = self.secondStr;
            dict[@"thirdTypeId"] = self.thirdStr;
            dict[@"albumName"] =self.albumNameTextField.text;
            [SVProgressHUD showWithStatus:@"重新归类中"];
            
            
            [RECheckLogin POST:REBaseUrl parameters:dict progress:^(CGFloat prosser) {
                
            } success:^(id responseObject) {
                if ([responseObject[@"result"] isEqualToString:@"0"]) {
                    [SVProgressHUD dismiss];
                    // 更新本地数据
                    BOOL isSuccess = [[RESingleton defaultCent] ModifyTheDateWithBaseUrl:self.baseModel.baseUrl
                                                                                firstStr:self.firstStr
                                                                               secondStr:self.secondStr
                                                                                thirdStr:self.thirdStr
                                                                               albumName:self.albumNameTextField.text
                                                                                titleStr:self.titleLabel.text];
                    if (isSuccess == YES) {
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateTheDatabase" object:nil];
                        [self.navigationController popViewControllerAnimated:YES];
                    }else
                    {
                        [SVProgressHUD showErrorWithStatus:@"更新数据库失败!!!!!"];
                    }
                }else
                {
//                    [SVProgressHUD showErrorWithStatus:responseObject[@"resultNote"]];
                }
                  [SVProgressHUD dismiss];
            } failure:^(NSError *error) {
                [SVProgressHUD showErrorWithStatus:@"查看网络!!!!!"];
            }];

        }
                // 获取曲目的id
            }
   }

-(void)creatFile
{
    
    
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:[RECheckLogin getDocumentPath:@"first"]]) {
        [[NSString stringWithFormat:@"%@,",self.firstStr]writeToFile:[RECheckLogin getDocumentPath:@"first"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }else
    {
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:[RECheckLogin getDocumentPath:@"first"]];
        [fileHandle seekToEndOfFile];  //将节点跳到文件的末尾
        NSData* stringData  = [[NSString stringWithFormat:@"%@,",self.firstStr] dataUsingEncoding:NSUTF8StringEncoding];
        [fileHandle writeData:stringData];
    }
    
  
    
    
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:[RECheckLogin getDocumentPath:@"second"]]) {
        [[NSString stringWithFormat:@"%@,",self.secondStr] writeToFile:[RECheckLogin getDocumentPath:@"second"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }else
    {    NSFileHandle *fileHandleTwo = [NSFileHandle fileHandleForUpdatingAtPath:[RECheckLogin getDocumentPath:@"second"]];
        [fileHandleTwo seekToEndOfFile];  //将节点跳到文件的末尾
        NSData* stringDataTwo  = [[NSString stringWithFormat:@"%@,",self.secondStr]  dataUsingEncoding:NSUTF8StringEncoding];
        [fileHandleTwo writeData:stringDataTwo];
        
    }

    
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:[RECheckLogin getDocumentPath:@"third"]]) {
        [[NSString stringWithFormat:@"%@,",self.thirdStr]  writeToFile:[RECheckLogin getDocumentPath:@"third"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }else
    {
        NSFileHandle *fileHandlethird = [NSFileHandle fileHandleForUpdatingAtPath:[RECheckLogin getDocumentPath:@"third"]];
        [fileHandlethird seekToEndOfFile];  //将节点跳到文件的末尾
        NSData* stringDatathird  = [[NSString stringWithFormat:@"%@,",self.thirdStr]  dataUsingEncoding:NSUTF8StringEncoding];
        [fileHandlethird writeData:stringDatathird];
    }

    
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.selfPlayer) {
            [self.selfPlayer pause];
            self.progressView.progress = 0.0;
            [self.selfPlayer.currentItem removeObserver:self  forKeyPath:@"status"];
            [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
            [self.palyButton setSelected:NO];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
